Ext.define('IAG.controller.SettingsInstanceController', {
    extend: 'Ext.app.Controller',

    stores: ['SettingsInstanceStore'],

    models: ['SettingsInstance'],

    views: ['settings.Settings'],
    init: function() {
    	console.log("Starting settings controller...");
    	
    	this.control({
            'settings': {
                itemdblclick: this.editSettingInstance
            },
            'editsettings button[action=saveSettings]' : {
            	click: this.updateSettingsInstance
            },
            'settings button[action=showAddSettings]' : {
            	click: this.showAddSetting
            },
            'settings button[action=reloadSettings]' : {
            	click: this.reload
            }
    	});
    },
    
    
    editSettingInstance: function (grid, record) {
    	console.log("Double-clicked setting");
    	  this.editView = Ext.create('IAG.view.settings.EditSettings').show();
          this.editView.down('form').loadRecord(record);
    },
    showAddSetting: function (button) {
   		this.newSettingsWin = Ext.create('IAG.view.settings.EditSettings');
    	
    	this.newSettingsWin.show();
    },
    updateSettingsInstance: function(button) {
        var win    = button.up('window'),
            form   = win.down('form');
        
        if (win == this.newSettingsWin) {
        	var record	= Ext.ModelManager.create(form.getValues(), 'IAG.model.SettingsInstance');
        	record.phantom	= true;
        	this.getStore("SettingsInstanceStore").add( record );
        	
        }
        else {
	        var record = form.getRecord();
	        var values = form.getValues();
	        record.set(values);
        }
        win.close();
    },
    getSettingsGrid: function () {
    	if ( this.settingsGrid == null ) {
    		this.settingsGrid	= Ext.create('IAG.view.settings.Settings');
    		this.getStore("SettingsInstanceStore").load();
    	}
    	return this.settingsGrid;
    },
    
    reload: function() {
    	this.getStore("SettingsInstanceStore").load();
    }

});